package scc.project.web.controller.manage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import scc.project.entity.StockInfo;
import scc.project.entity.vo.JsonVo;
import scc.project.entity.vo.PageVo;
import scc.project.entity.vo.RestFulPageVo;
import scc.project.entity.vo.StockInfoVo;
import scc.project.service.StockInfoService;
import scc.project.service.SupplierService;
import scc.project.util.HttpUtil;

import javax.servlet.http.HttpSession;

/**
 * 进货管理的控制器
 *
 * @author 陈圳佳
 *         日期：2015/6/22
 */
@Controller
@RequestMapping("/manage/stock")
public class StockController {

    @Autowired
    private StockInfoService stockInfoService;
    @Autowired
    private SupplierService supplierService;

    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    public String edit(ModelMap modelMap) {
        try {
            modelMap.addAttribute("sups", supplierService.getAll());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/manage/stock/edit";
    }

    @RequestMapping(value = "/list/{page}.html", method = RequestMethod.GET)
    public String list(@PathVariable("page") Integer page,
                       @RequestParam(value = "name", required = false)
                       String code, ModelMap modelMap) {
        System.out.print("已经进去了这个方法<><><><><><><>");
        PageVo<StockInfo> pageVo = null;
        try {
            pageVo = RestFulPageVo.convert(stockInfoService.find(page, code), ".html");
            pageVo.addProperty("data-pjax", "#content");
            modelMap.addAttribute("pageVo", pageVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/manage/stock/list";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JsonVo save(@RequestBody StockInfoVo siv,
                       HttpSession session) {
        JsonVo jsonVo = new JsonVo();
        try {
            siv.setEmpId(HttpUtil.getEmp(session).getId());
            boolean b = stockInfoService.save(siv);
            jsonVo.setStatus(b).setMsg(b ? "保存成功" : "保存失败原因未知");
        } catch (Exception e) {
            e.printStackTrace();
            jsonVo.setStatus(false).setMsg(e.getLocalizedMessage());
        }
        return jsonVo;
    }

}
